package com.nulldev.util.web.flexibleKit.scfk.testing;

import java.io.InputStream;
import java.security.Security;

import com.nulldev.util.JVM.Arguments;
import com.nulldev.util.JVM.JVM;
import com.nulldev.util.io.FastIO.FastIO;
import com.nulldev.util.io.file.FileUtil;
import com.nulldev.util.networking.misc.TLSUtil;
import com.nulldev.util.web.flexibleKit.scfk.SCFKRequest;
import com.nulldev.util.web.flexibleKit.scfk.SCFKResponse;
import com.nulldev.util.web.flexibleKit.scfk.io.streams.Stream;
import com.nulldev.util.web.flexibleKit.scfk.io.streams.StreamGenerator;
import com.nulldev.util.web.flexibleKit.scfk.protocols.http1.Http1Request;
import com.nulldev.util.web.flexibleKit.scfk.utils.ChannelTOSType;
import com.nulldev.util.web.flexibleKit.scfk.utils.TLSCipherPolicy;

public class HTTPSpeedTest {

	public static void main(String[] args) throws Exception {
		Arguments.setup(args);
		Security.setProperty("jdk.tls.disabledAlgorithms", "");
		Security.setProperty("jdk.tls.legacyAlgorithm", "");
		JVM.println("TLS Implemnentation: " + TLSUtil.getTLSImplementation());
		final SCFKRequest rq = new SCFKRequest("http://speedtest.tele2.net/10MB.zip");
		rq.setTOSPolicy(ChannelTOSType.TOS_THROUGHPUT);
		final Stream str = StreamGenerator.autoStream(rq, TLSCipherPolicy.ENABLE_ALL_CIPHERS);
		final SCFKResponse sf = new Http1Request().onRequestWrite(rq, str);
		final InputStream ois = sf.asStream();
		int r = 0, read = 0;
		final long len = sf.getContentLength();
		JVM.println("=> Content-Length: " + len);
		JVM.println("=> available (pre): " + ois.available());
		final byte[] data = new byte[16384];
		final long s = System.currentTimeMillis();
		while ((r = ois.read(data)) != -1 && read != len) {
			read += r;
			JVM.println("read: " + read + ", r: " + r);
			if (read == len)
				break;
		}
		final long e = System.currentTimeMillis();
		JVM.println("=> Downloaded.");
		if (read < 1024) {
			JVM.println(new String(data));
		}
		sf.close();
		JVM.println("=> Total read: " + read + " (" + FileUtil.convertToStringRepresentation(read) + ")");
		JVM.println("=> Time taken: " + (e - s) + " ms");
		FastIO.get().flush();
		JVM.exit();
	}

}
